<?php
namespace aliyun;
require_once 'autoload.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\RefererConfig;
use aliyun\MediaDemo;

class ossDemo {
    //默认配置
    protected $_config = array(
        'AccessKeyId'         => '',// 阿里云 AccessKeyId
        'AccessKeySecret'     => '',// 阿里云 AccessKeySecret
        'Endpoint'            => '',//地域节点
        'Bucket'              => ''//空间名称
    );

    /**
     * 获取配置信息
     * ossDemo constructor.
     */
    public function __construct()
    {
        if (config('aliyun')) {
            $this->_config = array_merge($this->_config, config('aliyun'));
        }
    }

    /**
     * 公共方法创建OssClient
     * @return OssClient
     */
    public function getOssClient(){
        $ossClient = new OssClient($this->_config['AccessKeyId'], $this->_config['AccessKeySecret'], $this->_config['Endpoint']);
        return $ossClient;
    }


    /**
     * @param $filePath // 由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
     * @param $object // 文件名称
     * @return string
     */
    public function uploadFile($filePath,$object,$type= 'image'){
        try{
            $this->getOssClient()->uploadFile($this->_config['Bucket'], $object, $filePath);
            if($type == 'video'){
                $play = new MediaDemo();
                $new_name = md5(time().uuid()).'.mp4';
                $sta = $play->videoTranscoding($object,$new_name);
                if($sta['code'] == 'Success'){
                    $object = $new_name;
                }
            }
            return $object;
        } catch(OssException $e) {
//            printf(__FUNCTION__ . ": FAILED\n");
            return $e->getMessage();
        }
//        print(__FUNCTION__ . ": OK" . "\n");
    }




    /**
     * 删除单个文件
     * @param $object
     * @return null|string
     */
    public function deleteObject($object){
        try{
           $this->getOssClient()->deleteObject($this->_config['Bucket'], $object);
        } catch(OssException $e) {
//            printf(__FUNCTION__ . ": FAILED\n");
//            printf($e->getMessage() . "\n");
            return $e->getMessage();
        }
    }



}